package com.itheima.reggie.controller;

import cn.hutool.core.lang.UUID;
import com.itheima.reggie.entity.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * <b><code>CommonController</code></b>
 * <p/>
 * 公共Controller
 * <p/>
 * <b>Creation Time:</b> 24/06/2024 16:39.
 *
 * @author yanjr
 * @since reggie_take_out
 */
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String filePath;

    @PostMapping("/upload")
    public R<String> uploadFile(MultipartFile file) {
        // file是一个临时文件，需要转存到指定为止，否则本次请求完成后临时文件会删除
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        // 使用UUID重新生成文件名，防止文件名重复导致文件覆盖
        String uuid = UUID.fastUUID().toString();
        String fileName = filePath + uuid + originalFilename.substring(originalFilename.lastIndexOf("."));

        try {
            // 创建一个目录
            File dir = new File(filePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 文件转存到新文件
            file.transferTo(new File(fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(uuid + originalFilename.substring(originalFilename.lastIndexOf(".")));
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        FileInputStream inputStream = null;
        ServletOutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(new File(filePath + name));
            int len = 0;
            byte[] bytes = new byte[1024];
            outputStream = response.getOutputStream();
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes);
            }
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try{
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
